angular.module('starter.controllers', [])

.controller('TabsCtrl', function($scope,Cart) {
	//首次加载首页显示购物车内商品
	$scope.cartItemCount=Cart.getCartItemCount();
	$scope.$on('cartItemCountChanged', function(event,data) {
		$scope.cartItemCount=Cart.getCartItemCount();
		console.log("recieved changed");
   	});
})

.controller('IndexCtrl', function($scope,ProductService,$ionicSlideBoxDelegate) {
	//推荐商品
	//$scope.recList=new Array();
	ProductService.findRec().then(function(result){
		//console.log(angular.toJson(result));
		$scope.recList=result.obj;
		//console.log($scope.recList);
		//$ionicSlideBoxDelegate.update重绘SlideBox
		$ionicSlideBoxDelegate.update();
	})
	//热门商品
	//$scope.hotList=[];
	ProductService.findHot().then(function(result){
		$scope.hotList=result.obj;
		//console.log($scope.hotList);
	})
})

.controller('CategoriesCtrl', function($scope,ProductService) {
	//$scope.categories=Categories.all();
	ProductService.findCategories().then(function(result){
		$scope.categories=result.obj;
		//console.log($scope.categories);
	});
})

.controller('GoodsTabsCtrl', function($scope, $ionicSlideBoxDelegate) {
	//设置selectedTab,tab绑定ng-class="{'active':selectedTab == 0}"用来设置tab的激活属性
	$scope.selectedTab = 0;
	//切换tab,设置selectTab,改变tab激活属性,同时切换slideBox
 	$scope.selectTabWithIndex = function(index) {
    	$scope.selectedTab = index; 
		$ionicSlideBoxDelegate.slide($scope.selectedTab);
  	}
 	//slideHasChanged后，子控制器把 index 冒泡到父控制器
 	$scope.$on('slideIndexChanged', function(event,data) {
 		//切换slide,设置selectTab,改变tab激活属性
    	$scope.selectedTab = data; 
   	});
})

.controller('GoodsListCtrl', function($scope,$timeout,$ionicSlideBoxDelegate,$stateParams,ProductService,Cart,$rootScope) {
	//获得csid
	$scope.csid=$stateParams.csid;
	//首次加载,监听stateChange来判断
	$scope.$on('$stateChangeSuccess', function() {
    	$scope.init();
   	});
	//初始化函数
	$scope.init=function(){
		//初始化商品列表
		$scope.productList=[];
		//初始化当前页码数为0
		$scope.page=0;	
		//首次拉取数据
		$scope.loadMore();
		//ion-content滚动到顶部 用这个导致$digest报错
		//$ionicScrollDelegate.scrollTop();
	}
	
	//切换新品、热卖、价格：1、清空商品列表 2、初始化页码   根据index对应的属性product排序
	//切换slidebox,重新加载商品列表,向父级冒泡改变后的index值
	$scope.slideHasChanged = function(index) {
 		$scope.$emit('slideIndexChanged', index);
 		$scope.init();
  	}

	//上拉加载更多
	$scope.loadMore=function(){
		$timeout(function(){
			//每次加载更多，页码加1
			$scope.page++;
			ProductService.findByCsid($scope.csid,$scope.page,$ionicSlideBoxDelegate.currentIndex()).then(function(result){
				//获得总页码数
				$scope.pageCount=result.obj.totalPage;
				//当前数组拼接新数组
				$scope.productList=$scope.productList.concat(result.obj.list);
				//加载完更多内容后广播
				$scope.$broadcast('scroll.infiniteScrollComplete');
				//console.log($scope.productList);
			})	
		},500);
		console.log("我调用的？");
	}
	
	//上拉加载超过总页码数则返回false,不允许再加载
	$scope.moreDataCanBeLoaded=function(){
		if($scope.page<$scope.pageCount)
			return true;
		else
			return false;
	}
	
	//加入购物车
	$scope.addCart=function(index){
		console.log($scope.productList[index]);
		$scope.cartItem={product:$scope.productList[index],quantity:1};
		console.log("before addCart:"+$scope.cartItem);
		Cart.addCart($scope.cartItem);
		$rootScope.$broadcast('cartItemCountChanged');
	}
})

.controller('GoodsInfoCtrl', function($scope,$stateParams,ProductService,Cart,$rootScope,$ionicSlideBoxDelegate) {
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})
	
	$scope.quantity=1;
	$scope.product={};
	ProductService.findByPid($stateParams.pid).then(function(result){
		$scope.product=result.obj;
		$scope.imgs=result.obj.imgs;
		//ion-slide-box使用ng-repeat时，载入图片发生改变时，需要重绘
		$ionicSlideBoxDelegate.update();
	});
	$scope.decrement = function() {
  		if($scope.quantity<=1)
  			return;
  		$scope.quantity--;
  	}
	$scope.increment = function() {
 		$scope.quantity++;
	}
	$scope.addCart=function(){
		$scope.cartItem={product:$scope.product,quantity:$scope.quantity};
		console.log("before addCart:"+$scope.cartItem);
		Cart.addCart($scope.cartItem);
		$rootScope.$broadcast('cartItemCountChanged');
	}
	
})

.controller('GoodsDetailCtrl', function($scope,$stateParams,ProductService) {
	ProductService.findByPid($stateParams.pid).then(function(result){
		$scope.pdescimgs=result.obj.pdescimgs;
		console.log($scope.pdescimgs);
	});
})


.controller('MeCtrl', function($scope,AuthService,Session) {
	$scope.isLogin=Session.authorized;
	if($scope.isLogin){
		$scope.user=Session.currentUser;
		console.log("user:"+$scope.user);
	}
})

.controller('RegistCtrl', function($scope,$state,$ionicPopup,AuthService,$ionicHistory) {
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})
	$scope.user={username:"",email:"",password:"",confirmPwd:""};
	$scope.message="";
	$scope.regist=function(){
		if($scope.user.username==""){
			$scope.message="用户名不能为空！";
			$scope.showPopup();
			return;
		}
		if($scope.user.email==""){
			$scope.message="邮箱不能为空！";
			$scope.showPopup();
			return;
		}
		if($scope.user.password==""){
			$scope.message="密码不能为空！";
			$scope.showPopup();
			return;
		}
		if($scope.user.password!=$scope.user.confirmPwd)//如果两次密码输入不一致,提示并返回
		{
			$scope.message="两次输入密码不一致！";
			$scope.showPopup();
			return;
		}
		
		AuthService.register($scope.user).then(function(result){
			console.log(result);
			if(result.result==0)
			{
				$scope.message=result.desc;
				$scope.showPopup();
				return;
			}
			$scope.message="注册成功，请登录邮箱激激活账号后再登录！";
			$scope.showPopup();
			//$ionicHistory.goBack();
			$state.go('tab.me');
		});
	}
	
	// 显示定制弹出框，提示错误消息
	$scope.showPopup = function() {
		// 调用$ionicPopup弹出定制弹出框
		$ionicPopup.show({
			template: $scope.message,
			title: "提示",
			buttons: [
				{
					text: "确认",
					type: "button-balanced"
				}
			]
		})
	};

})

.controller('LoginCtrl',function($scope,$state,$ionicPopup,$ionicHistory,AuthService,Session){
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})
	$scope.user={username:"",password:""};
	$scope.login=function(){
		AuthService.login($scope.user).then(function(result){
			console.log("result:"+angular.toJson(result));
			if(result.result==0)
			{
				$scope.message=result.desc;
				$scope.showPopup();
				return;
			}
			//登录成功
			Session.create(result.obj);//记录用户信息在Session.currentUser中
			Session.remember($scope.user);//保存用户名密码
			$scope.user=Session.currentUser;
			$scope.isLogin=true;//当前用户登录状态置为true
			$scope.message="登录成功";
			$scope.showPopup();
			$ionicHistory.goBack();
			//$ionicHistory.clearCache();
		});
	}
	
	// 显示定制弹出框，提示错误消息
	$scope.showPopup = function() {
		// 调用$ionicPopup弹出定制弹出框
		$ionicPopup.show({
			template: $scope.message,
			title: "提示",
			buttons: [
				{
					text: "确认",
					type: "button-balanced"
				}
			]
		})
	};
	
})


.controller('SettingsCtrl', function($scope,Session,AuthService,$ionicHistory,$state) {
	//判断用户是否登录
	$scope.isLogin=Session.authorized;
	$scope.logout=function(){
		Session.destroy();//注销
		$scope.isLogin=Session.authorized;
		$state.go('tab.me');
		//$ionicHistory.clearCache();
		//$cordovaToast.show('账号已登出', 'long', 'center');
	}	
})

.controller('CartCtrl', function($scope,Cart,$ionicPopup,Session,$state,$rootScope) {
	$scope.cart=Cart.getCart();
	$scope.total=Cart.getTotal();
	console.log("total:"+$scope.total);
	$scope.decrement = function(index) {
		//当商品数量小于1则从购物车移除
  		if($scope.cart[index].quantity<=1){
  			Cart.removeCart($scope.cart[index].product.pid);
  		}
  		else{
  			Cart.decrement($scope.cart[index].product.pid);	
  		}  		
  		$scope.cart=Cart.getCart();
  		$scope.total=Cart.getTotal();
  		//总商品数量减1并冒泡到父类
  		$rootScope.$broadcast('cartItemCountChanged');
  	}
	$scope.increment = function(index) {
 		Cart.increment($scope.cart[index].product.pid);
  		$scope.cart=Cart.getCart();
  		$scope.total=Cart.getTotal();
  		//总商品数量加1并冒泡到父类
  		$rootScope.$broadcast('cartItemCountChanged');
	}
	//提交订单
	$scope.submitOrder=function(){
		if(Cart.getCart().length<=0){
			$scope.message="购物车为空，请先添加商品！";
			$scope.showPopup();
			return;
		}
		if(Session.authorized){
			$state.go('order');						
		}
		else{
			$scope.message="请先登录！";
			$scope.showPopup();
			$state.go('tab.me');
		}
	}
	// 显示定制弹出框，提示错误消息
	$scope.showPopup = function() {
		// 调用$ionicPopup弹出定制弹出框
		$ionicPopup.show({
			template: $scope.message,
			title: "提示",
			buttons: [
				{
					text: "确认",
					type: "button-balanced"
				}
			]
		})
	};
})

.controller('OrderCtrl', function($scope,Cart,Session,$state,$rootScope) {
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})
	if(!Session.authorized){
		$state.go('tab.login');
	}
	$scope.user=Session.currentUser;
	$scope.cart=Cart.getCart();
	$scope.total=Cart.getTotal();
	$scope.saveOrder=function(){
		//看服务端需要什么样的信息，这边就拼接什么的样的信息传递过去
		Cart.saveOrder($scope.user).then(function(result){
			console.log("order-result:"+angular.toJson(result));
			if(result.result==1){
				//清空购物车
				Cart.clearCart();
				$rootScope.$broadcast('cartItemCountChanged');
				$state.go('orderok',{oid:result.obj.oid});
			}
		});
	}
})

.controller('OrderOkCtrl', function($scope,OrderService,$stateParams,$ionicScrollDelegate,$state) {
	$scope.payOrder=function(){
		OrderService.payOrder($stateParams.oid).then(function(result){
			if(result.result==1){
				$state.go('tab.me');
			}
		});
	}
})

.controller('MyOrdersCtrl', function($scope,$timeout,$state,OrderService,Session) {
	if(!Session.authorized){
		$state.go('tab.me');
		return;
	}
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})

	$scope.$on('$stateChangeSuccess', function() {
    	//首次拉取数据
		$scope.loadMore();
   	});	
	$scope.user=Session.currentUser;
	//初始化订单列表
	$scope.orderList=[];
	//初始化当前页码数为0
	$scope.page=0;	
	//ion-content滚动到顶部
	//$ionicScrollDelegate.scrollTop();

	//上拉加载更多
	$scope.loadMore=function(){
		$timeout(function(){
			//每次加载更多，页码加1
			$scope.page++;
			console.log($scope.page);
			OrderService.getAll($scope.user.uid,$scope.page).then(function(result){
				//获得总页码数
				$scope.pageCount=result.obj.totalPage;
				//当前数组拼接新数组
				$scope.orderList=$scope.orderList.concat(result.obj.list);
				//加载完更多内容后广播
				$scope.$broadcast('scroll.infiniteScrollComplete');
				//console.log($scope.productList);
			})	
		},500);
	}
	
	//上拉加载超过总页码数则返回false,不允许再加载
	$scope.moreDataCanBeLoaded=function(){
		if($scope.page<$scope.pageCount)
			return true;
		else
			return false;
	}
	
	//刷新函数
  	$scope.doRefresh = function() {
  		$scope.user=Session.currentUser;
		//初始化订单列表
		$scope.orderList=[];
		//初始化当前页码数为0
		$scope.page=0;	
  		$scope.loadMore();
	    $timeout(function(){
	    	$scope.$broadcast('scroll.refreshComplete');
	    }, 500);
   	};
})

.controller('OrderDetailCtrl', function($ionicPopup,$timeout,$scope,$stateParams,$state,OrderService,Session) {
	var oid=$stateParams.oid;
	//切换到本页面即执行
	$scope.$on('$stateChangeSuccess', function() {
    	init();
   	});	

	var init=function(){
		//获取订单详情
		OrderService.findByOid(oid).then(function(result){
			if(result.result==1){
				$scope.order=result.obj;
				switch(result.obj.state){
					case 0:
						$scope.notpaid=true;
						$scope.ontheway=false;
						break;
					case 1:
						$scope.notpaid=false;
						$scope.ontheway=false;
						break;
					case 2:
						$scope.notpaid=false;
						$scope.ontheway=false;
						break;
					case 3:
						$scope.notpaid=false;
						$scope.ontheway=true;
						break;
					case 4:
						$scope.notpaid=false;
						$scope.ontheway=false;
						break;
				}
			}
		});	
		//获取订单项列表
		OrderService.findOrderItem(oid).then(function(result){
			if(result.result==1){
				$scope.orderItems=result.obj;
			}
		});
	}

	//支付订单
	$scope.payOrder=function(){
		OrderService.payOrder(oid).then(function(result){
			if(result.result==1){
				init();
				$scope.message="支付成功！";
				$scope.showPopup();
			}
		});
	}
	//确认收货
	$scope.updateState=function(){
		OrderService.updateState(oid).then(function(result){
			if(result.result==1){
				init();
				$scope.message="确认收货！";
				$scope.showPopup();
			}
		});
	}
	
	//刷新函数
  	$scope.doRefresh = function() {
	    $timeout(function(){
			init();
	    	$scope.$broadcast('scroll.refreshComplete');
	    }, 500);
   	}
   	
   	// 显示定制弹出框，提示错误消息
	$scope.showPopup = function() {
		// 调用$ionicPopup弹出定制弹出框
		$ionicPopup.show({
			template: $scope.message,
			title: "提示",
			buttons: [
				{
					text: "确认",
					type: "button-balanced"
				}
			]
		})
	};
})

.controller('SearchCtrl', function($scope,ProductService,$rootScope,$timeout,Cart) {
	//显示回退按钮←
	$scope.$on('$ionicView.beforeEnter',function(evt,enteringData){
		enteringData.enableBack=true;
	})
	
	//定义ng-model对象
	$scope.name={value:""};
	$scope.productList = [];
	var page;
	var pageCount;
	
	$scope.search=function(){
		page=0;
		ProductService.findByName($scope.name.value,1).then(function(result){
			//获得总页码数
			pageCount=result.obj.totalPage;
			//当前数组拼接新数组
			$scope.productList=$scope.productList.concat(result.obj.list);
			//加载完更多内容后广播
			$scope.$broadcast('scroll.infiniteScrollComplete');
		});	
	}
	
	$scope.loadMore = function(){
		page++;
		$timeout(function(){
			ProductService.findByName($scope.name.value,page).then(function(result){
			//获得总页码数
			pageCount=result.obj.totalPage;
			//当前数组拼接新数组
			$scope.productList=$scope.productList.concat(result.obj.list);
			//加载完更多内容后广播
			$scope.$broadcast('scroll.infiniteScrollComplete');
		});	
		},500);
	};
	$scope.moreDataCanBeLoaded=function(){
		if(page<pageCount)
			return true;
		else
			return false;
	}
		
	//加入购物车
	$scope.addCart=function(index){
		console.log($scope.productList[index]);
		$scope.cartItem={product:$scope.productList[index],quantity:1};
		console.log("before addCart:"+$scope.cartItem);
		Cart.addCart($scope.cartItem);
		$rootScope.$broadcast('cartItemCountChanged');
	}
})
